<?php
declare(strict_types=1);

namespace app\service;

use app\model\{MessageTemplateConfig, PlatformConfig};
use think\facade\Log;

class SmsService
{
    protected $merchantId;
    protected $platformConfig;
    
    public function __construct(int $merchantId)
    {
        $this->merchantId = $merchantId;
        // 获取平台短信配置
        $this->platformConfig = PlatformConfig::where('group_name', 'sms')
            ->column('config_value', 'config_key');
    }

    /**
     * 发送验证码短信
     * @param string $mobile 手机号
     * @param int $code 验证码
     * @return bool
     */
    public function sendCode(string $mobile, int $code): bool
    {
        try {
            // 获取商家短信验证码模板配置
            $template = MessageTemplateConfig::where([
                'merchant_id' => $this->merchantId,
                'message_type' => 3, // 短信类型
                'message_setting_id' => 1 // 验证码场景ID
            ])->find();

            if (!$template) {
                throw new \Exception('未配置短信验证码模板');
            }

            // 准备模板参数
            $params = [
                'code' => $code,
                'expire' => '5', // 有效期5分钟
            ];

            // 根据平台配置的服务商发送短信
            $provider = $this->platformConfig['sms_provider'] ?? 'aliyun';
            
            switch ($provider) {
                case 'aliyun':
                    return $this->sendAliyunSms($mobile, $template->template_id, $params);
                case 'tencent':
                    return $this->sendTencentSms($mobile, $template->template_id, $params);
                default:
                    throw new \Exception('未配置短信服务商');
            }
        } catch (\Exception $e) {
            Log::error('发送短信验证码失败', [
                'merchant_id' => $this->merchantId,
                'mobile' => $mobile,
                'error' => $e->getMessage()
            ]);
            return false;
        }
    }
    
    /**
     * 发送阿里云短信
     */
    protected function sendAliyunSms(string $mobile, string $templateId, array $params): bool
    {
        try {
            // 配置阿里云客户端
            AlibabaCloud::accessKeyClient(
                $this->platformConfig['aliyun_access_key_id'],
                $this->platformConfig['aliyun_access_key_secret']
            )->regionId('cn-hangzhou')->asDefaultClient();
            
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->options([
                    'query' => [
                        'PhoneNumbers' => $mobile,
                        'SignName' => $this->platformConfig['aliyun_sign_name'],
                        'TemplateCode' => $templateId,
                        'TemplateParam' => json_encode($params)
                    ],
                ])
                ->request();
                
            $success = $result->Code === 'OK';
            
            // 记录发送日志
            Log::info('阿里云短信发送结果', [
                'merchant_id' => $this->merchantId,
                'mobile' => $mobile,
                'template_id' => $templateId,
                'params' => $params,
                'result' => $result->toArray()
            ]);
            
            return $success;
            
        } catch (\Exception $e) {
            Log::error('阿里云短信发送异常', [
                'merchant_id' => $this->merchantId,
                'mobile' => $mobile,
                'error' => $e->getMessage()
            ]);
            return false;
        }
    }
    
    /**
     * 发送腾讯云短信
     */
    protected function sendTencentSms(string $mobile, string $templateId, array $params): bool
    {
        try {
            $cred = new Credential(
                $this->platformConfig['tencent_secret_id'],
                $this->platformConfig['tencent_secret_key']
            );
            
            $client = new SmsClient($cred, "ap-guangzhou");
            
            $req = new SendSmsRequest();
            $req->SmsSdkAppId = $this->platformConfig['tencent_sdk_app_id'];
            $req->SignName = $this->platformConfig['tencent_sign_name'];
            $req->TemplateId = $templateId;
            $req->PhoneNumberSet = ["+86".$mobile];
            $req->TemplateParamSet = array_values($params);
            
            $resp = $client->SendSms($req);
            
            $success = $resp->SendStatusSet[0]->Code === "Ok";
            
            // 记录发送日志
            Log::info('腾讯云短信发送结果', [
                'merchant_id' => $this->merchantId,
                'mobile' => $mobile,
                'template_id' => $templateId,
                'params' => $params,
                'result' => $resp->toArray()
            ]);
            
            return $success;
            
        } catch (\Exception $e) {
            Log::error('腾讯云短信发送异常', [
                'merchant_id' => $this->merchantId,
                'mobile' => $mobile,
                'error' => $e->getMessage()
            ]);
            return false;
        }
    }
}
